package com.sad.jetpack.v1.datamodel.api.extension.client.http.sse;

import com.sad.jetpack.v1.datamodel.api.DataModelProducerImpl;
import com.sad.jetpack.v1.datamodel.api.IDataModelProducer;
import com.sad.jetpack.v1.datamodel.api.IDataModelRequest;
import com.sad.jetpack.v1.datamodel.api.extension.client.DataClient;
import com.sad.jetpack.v1.datamodel.api.extension.interceptor.LogDataModelInterceptor;

public class SSEDataClient extends DataClient<SSEDataClient,String> {
    private SSEConnectionListener connectionListener;
    private AbsSSEEngine engine=new DefaultOkHttpSSEEngine();
    private SSEDataClient(){}
    public static SSEDataClient newInstance(){
        return new SSEDataClient();
    }
    public SSEDataClient connectionListener(SSEConnectionListener connectionListener){
        this.connectionListener=connectionListener;
        return this;
    }
    public SSEDataClient engine(AbsSSEEngine engine){
        this.engine=engine;
        return this;
    }
    @Override
    public IDataModelProducer<String> dataModelProducer(String tagAndClientKey) {
        IDataModelRequest request=requestCreator.tag(tagAndClientKey).create();
        LogDataModelInterceptor logInterceptor = LogDataModelInterceptor.newInstance();
        IDataModelProducer<String> dataModelProducer = DataModelProducerImpl.<String>newInstance();
        if (isInternalLog()){
            dataModelProducer.addInputInterceptor(logInterceptor).addOutputInterceptor(logInterceptor);
        }
        AbsSSEEngine sseEngine=engine==null?new DefaultOkHttpSSEEngine():engine;
        engine=sseEngine;
        sseEngine.setConnectionListener(connectionListener);
        dataModelProducer
                .newRequest(request)
                .engine(sseEngine);
        return dataModelProducer;
    }

    public AbsSSEEngine getEngine() {
        return engine;
    }
}
